package com.cavy.platform.server.service;

import com.cavy.platform.server.ResultList;
import com.cavy.platform.server.domain.Plugin;
import com.cavy.platform.server.dto.*;
import com.cavy.platform.server.mapper.PluginMapper;
import com.cavy.platform.server.repository.PluginRepository;
import com.cavy.platform.server.util.HttpServletResponseHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * Created by tangxu on 18-7-10.
 */
@Service
public class PluginService {

    @Autowired
    private PluginRepository repository;

    public void create(PluginCreateDto dto) throws IOException {
        repository.create(PluginMapper.INSTANCE.convertToPlugin(dto));
    }

    public void modify(PluginModifyDto dto) throws IOException {
        repository.deleteInfo(dto.getName(), dto.getVersion());
        repository.create(PluginMapper.INSTANCE.convertToPlugin(dto));
    }

    public void delete(PluginDeleteDto dto) {
        repository.delete(dto.getName(), dto.getVersion());
    }

    public ResultList list(PluginSearchDto dto) {
        return repository.list(dto);
    }

    public String[] versionList(String name) {
        return repository.getVersionList(name);
    }

    public PluginDto info(String name, String version) throws IOException {
        if (Plugin.LATEST_VERSION.equalsIgnoreCase(version)) {
            version = getLastVersion(name);
        }
        Plugin info = repository.info(name, version);
        return PluginMapper.INSTANCE.convertToPluginDto(info);
    }

    private String getLastVersion(String name) {
        String version;
        String[] versionList = repository.getVersionList(name);
        version = versionList[0];
        return version;
    }

    public void logo(String name, HttpServletResponse response) {
        String lastVersion = getLastVersion(name);
        File logo = repository.getLogo(name, lastVersion);
        if (logo.exists()) {
            writeFileToResponse(response, logo);
        }
    }

    private void writeFileToResponse(HttpServletResponse response, File file) {
        response.setHeader("filePath", file.getPath());
        HttpServletResponseHelper.writeFile(file, response);
    }

    public ResultList refresh(PluginSearchDto searchDto) {
        repository.refresh();
        return repository.list(searchDto);
    }

    public void uploadLogo(PluginLogoUploadDto uploadDto) {
        repository.saveLogo(uploadDto.getName(), uploadDto.getVersion(), uploadDto.getFile());
    }
}
